<?php
namespace App\Http\Controllers\Api;

use App\Models\Bureau\WxBureau;
use App\Models\Bureau\WxClubTeam;
use App\Models\WxWallpapersComment;
use App\Wen\Utils\BaiduUtils;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use App\Models\User\WxUser;
use App\Models\WxWallpaper;
use Illuminate\Http\Request;

class WallpaperController extends BaseController
{
    public function detail(Request $request)
    {
        $id = $request->id;
        if(_empty_($id)){
            return $this->fail(200001);
        }
        $WxWallpaper = WxWallpaper::leftJoin('wx_wallpapers_subject', 'wx_wallpapers_subject.id', 'wx_wallpapers.subject_id')->where('wx_wallpapers.id', $id)->orderBy('wx_wallpapers.id', 'desc')->first();
        if(_empty_($WxWallpaper)){
            return $this->fail(200003);
        }
        $uid = $request->uid;
        $WxWallpaper->comment_count = WxWallpapersComment::where('wallpaper_id', $WxWallpaper->id)->where('comment_state', 1)->count();
        $collected_wallpaper = get_user_meta($uid, 'collected_wallpaper', 'j');
        $this->userAndImgsProcess($WxWallpaper, $collected_wallpaper);
        return $this->success($WxWallpaper);
    }

    public function comment_process(Request $request){
        $action = _empty_default_($request->action, '');
        $uid = $request->uid;
        if(_empty_($action)){
            return $this->fail(200001);
        }
        if(!in_array($action, ['add', 'delete'])){
            return $this->fail(200004);
        }

        if(!UserUtils::is_user_can_speak($uid)){
            return $this->fail(200043, [
                'title' => '禁言中，无法言论',
                'content' => '是否前往解除限制',
                'confirmText' => '去解除',
                'target_type' => 6,
                'target_id' => '/pagesA/mine/unlock/unlock?user_id='.$uid
            ], '您当前处于禁言期间，无法言论');
        }


        if($action == 'add'){

            $wallpaper_id = _empty_default_($request->wallpaper_id, 0);
            if(_empty_($wallpaper_id)){
                return $this->fail(200001);
            }

            if(!WxWallpaper::where('id', $wallpaper_id)->exists()){
                return $this->fail(200000, [], '该图集不存在');
            }

            if(mb_strlen( str_replace( [Settings::get('default_user_name', '微信用户'), '微信用户', '普通用户'], '', UserUtils::get_cached_user_name($uid) )) != mb_strlen(UserUtils::get_cached_user_name($uid))){
                return $this->fail(200041);
            }

            $comment_id = _empty_default_($request->comment_id, 0);
            if(_empty_($comment_id)){
                $comment_id = 0;
            }

            if($comment_id > 0){
                if(!WxWallpapersComment::where('id', $comment_id)->where('comment_state', 1)->exists()){
                    return $this->fail(200004, [], '该父级评论不存在');
                }
            }


            $comment_agent_id = _empty_default_($request->comment_agent_id, 0);
            if(_empty_($comment_agent_id)){
                $comment_agent_id = 0;
            }
            if($comment_agent_id > 0){
                $comment_agent_name = UserUtils::get_cached_user($comment_agent_id)['user_name'];
            }

            $comment_content = _empty_default_($request->comment_content, '');
            $comment_img_url = _empty_default_($request->comment_img_url, '');

            if(_empty_($comment_content)){
                return $this->fail(200001);
            }

            $comment_content = strip_tags($comment_content);
            if(mb_strlen($comment_content) <= 0 || mb_strlen($comment_content) > 240){
                return $this->fail(200004, [], '评论内容过长或过短');
            }

            global $__MINI_GLOBAL_IP__;

            // 百度审核
            if(UserUtils::user_permissions_check_by_config($uid, 'audit_used_comment_white_list')){
                $need_manual_review = false;
            }else{
                $need_manual_review = true;
                $is_audit_used_comment = Settings::get('is_audit_used_comment', 0);
                if ($is_audit_used_comment == 2) {
                    $filter_result = BaiduUtils::text_filter($comment_content);
                    if($filter_result){
                        if($filter_result['hit_level'] == 2){
                            // 不合规
                            return $this->fail(200016, ['tip'=>$filter_result['tip_list'], 'hit_word'=>$filter_result['hit_word']]);
                        }else if($filter_result['hit_level'] == 0){
                            // 审核通过
                            $need_manual_review = false;
                        }
                    }
                }else if($is_audit_used_comment == 0){
                    $need_manual_review = true;
                }else{
                    $need_manual_review = false;
                }
            }

            // 0:审核中，1:审核通过，2:驳回
            $comment_state = 1;
            if($need_manual_review){
                $comment_state = 0;
            }


            $model = new WxWallpapersComment();
            $model->user_id = $uid;
            $model->wallpaper_id = $wallpaper_id;
            if($comment_id > 0){
                $model->comment_id = $comment_id;
            }else{
                $model->comment_id = 0;
            }
            if($comment_agent_id > 0 && $comment_agent_name){
                $model->comment_agent_id = $comment_agent_id;
                $model->comment_agent_name = $comment_agent_name;
            }else{
                $model->comment_agent_id = 0;
            }

            $model->comment_content = $comment_content;
            if(!_empty_($comment_img_url)){
                $model->comment_img_url = $comment_img_url;
            }

            if($__MINI_GLOBAL_IP__){
                $model->ip = $__MINI_GLOBAL_IP__;
            }
            $model->comment_state = $comment_state;
            $r = $model->save();
            if($r){
                return $this->success();
            }
            return $this->fail(200002);
        }else if($action == 'delete'){

        }
    }

    public function comment_list(Request $request){
        $limit = _between_(_empty_default_($request->limit, 10), 1, 100);
        $wallpaper_id = _empty_default_($request->wallpaper_id, 0);
        if(_empty_($wallpaper_id)){
            $this->fail(200001);
        }
        $data = WxWallpapersComment::where('wallpaper_id', $wallpaper_id)->where('comment_id', 0)->where('comment_state', 1)->orderBy('id', 'desc')->simplePaginate($limit);
        if($data){
            $data->map(function ($v, $k){
                $v->user = UserUtils::get_cached_user($v->user_id);
                if(_empty_($v->comment_id)){
                    $childData = WxWallpapersComment::where('comment_id', $v->id)->limit(100)->get();
                    if($childData){
                        $childData->map(function ($v2, $k2){
                            $v2->user = UserUtils::get_cached_user($v2->user_id);
                            $v2->format_time = format_datetime($v2->created_at);
                            return $v2;
                        });
                    }
                    $v->child = $childData;
                }else{
                    $v->child = [];
                }
                $v->format_time = format_datetime($v->created_at);
                return $v;
            });
            return $this->success($data);
        }else{
            return $this->fail(200003);
        }
    }

    public function list(Request $request){
        $type = _empty_default_($request->type, 'subject');
        $uid = $request->uid;
        if(_empty_($type)){
            $type = 'subject';
        }
        if(!in_array($type, ['subject', 'bureau'])){
            return $this->fail(200004);
        }
        $bureau_id = _empty_default_($request->bureau_id, 0);
        $collected = _empty_default_($request->collected, 0);
        if($type == 'bureau'){
            $query = WxWallpaper::where('bureau_id', $bureau_id);
        }else{
            $query = WxWallpaper::whereNull('bureau_id');
            if($collected == 1){
                if(_empty_($uid)){
                    return $this->fail(503002);
                }
                $collected_wallpaper = get_user_meta($uid, 'collected_wallpaper', 'j');
                if($collected_wallpaper){
                    $query = $query->whereIn('id', array_reverse($collected_wallpaper));
                }
            }
        }
        $WxWallpapers = $query->orderBy('id', 'desc')->simplePaginate();
        if(_empty_($WxWallpapers)){
            return $this->fail(200003);
        }
        $uid = Utils::uid($request);
        $collected_wallpaper = get_user_meta($uid, 'collected_wallpaper', 'j');

        $WxWallpapers->map( function ($item) use(&$collected_wallpaper) {
            $this->userAndImgsProcess($item, $collected_wallpaper);
            $item->comment_count = WxWallpapersComment::where('wallpaper_id', $item->id)->where('comment_state', 1)->count();
            return $item;
        } );
        return $this->success($WxWallpapers);
    }

    private function userAndImgsProcess(&$WxWallpaper, &$collected_wallpaper){
        $WxWallpaper->imgs = json_decode($WxWallpaper->imgs ?: '', true);
        $WxWallpaper->author = WxUser::where('id', $WxWallpaper->user_id)->get(FieldUtils::userInfoColums());
        $WxWallpaper->iscollect = $collected_wallpaper ? in_array($WxWallpaper->id, $collected_wallpaper) : 0;
        $WxWallpaper->firstImg = $WxWallpaper->imgs ? $WxWallpaper->imgs[0] : '';
        $WxWallpaper->imgNum = $WxWallpaper->imgs ? count($WxWallpaper->imgs) : 0;
    }

    public function wallpaper_process(Request $request) {
        $type = _empty_default_($request->type, '');
        if ($type == 'collect') {
            return $this->collect($request);
        }else if ($type == 'add') {
            return $this->add($request);
        }
    }


    private function add(Request $request){
        $uid = $request->uid;
        $id = _empty_default_($request->id, 0);
        $bureau_id = _empty_default_($request->bureau_id, 0);
        $title = _empty_default_($request->title, '');
        $imgs = _empty_default_($request->imgs, '');

        $latitude = _empty_default_($request->latitude, 0);
        $longitude = _empty_default_($request->longitude, 0);
        $address_name = _empty_default_($request->address_name, '');
        $address_detailed = _empty_default_($request->address_detailed, '');


        global $__MINI_GLOBAL_IP__;
        if(_empty_($imgs)){
            $imgs = '';
        }
        if(is_string($imgs)){
            $imgs = explode(',', $imgs);
        }
        if(!is_array($imgs)){
            $imgs = [];
        }
        if(_empty_($imgs)){
            return $this->fail(200001, [], '请上传图片');
        }
        if(_empty_($title)){
            return $this->fail(200001, [], '请填写描述');
        }
        if($id > 0){
            return $this->fail(200004, [], '暂时不能处理修改图集');
        }

        $img_state_change = [];
        foreach ($imgs as $img_url){
            if(!StrUtils::startsWith($img_url, 'http')){
                return $this->fail(200004, [], '图片检验出错');
            }
            $img_state_change[] = $img_url;
        }

        if($bureau_id > 0){
            $bureau = WxBureau::find($bureau_id);
            if(!$bureau){
                return $this->fail(200003, [], '组局活动不存在');
            }
            if(!(WxClubTeam::where('bureau_id', $bureau_id)->where('members', 'like', "%'".$uid."'%")->exists()) && $uid != $bureau->user_id && !UserUtils::is_mini_supder_admin($uid)){
                return $this->fail(200000, [], '您没有参加该次活动，不能发布图集');
            }
        }

        $wallpaper = new WxWallpaper();
        if($bureau_id > 0){
            $wallpaper->bureau_id = $bureau_id;
        }
        $wallpaper->title = $title;
        $wallpaper->imgs = json_encode($imgs);
        $wallpaper->user_id = $uid;
        $wallpaper->ip = $__MINI_GLOBAL_IP__;
        if(!_empty_($address_detailed) && _empty_($address_name)){
            $wallpaper->latitude = $latitude;
            $wallpaper->longitude = $longitude;
            $wallpaper->address_name = $address_name;
            $wallpaper->address_detailed = $address_detailed;
        }
        $r = $wallpaper->save();
        if($r){
            Utils::image_state_change($img_state_change);
            return $this->success($wallpaper->id);
        }
        return $this->fail(200002);
    }

    private function collect(Request $request){
        $uid = $request->uid;
        $id = $request->id;
        if(_empty_($id)){
            return $this->fail(200001);
        }

        $collected_wallpaper = get_user_meta($uid, 'collected_wallpaper', 'j');
        if(_empty_($collected_wallpaper)){
            $collected_wallpaper = [];
        }

        if(in_array($id, $collected_wallpaper)){
            foreach($collected_wallpaper as $k=>$v){
                if($v == $id){
                    unset($collected_wallpaper[$k]);
                    break;
                }
            }
            if(update_user_meta($uid, 'collected_wallpaper', $collected_wallpaper, 'j')){
                return $this->success(['isCollect'=>0, 'msg'=>'已取消']);
            }else{
                return $this->fail(200002);
            }

        }else{

            $collected_wallpaper[] = $id;
            if(update_user_meta($uid, 'collected_wallpaper', $collected_wallpaper, 'j')){
                return $this->success(['isCollect'=>1, 'msg'=>'收藏成功']);
            }else{
                return $this->fail(200002);
            }

        }

    }

}
